package com.yixueyun.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.yixueyun.ucenter.mapper.YxyMenuMapper;
import com.yixueyun.ucenter.mapper.YxyUserMapper;
import com.yixueyun.ucenter.model.dto.AuthParamsDto;
import com.yixueyun.ucenter.model.dto.YxyUserExt;
import com.yixueyun.ucenter.model.po.YxyMenu;
import com.yixueyun.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 *security实现自定义的userService
 *
 */
@Slf4j
@Component
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    private YxyUserMapper yxyUserMapper;
    @Autowired
    private YxyMenuMapper yxyMenuMapper;
    @Autowired
    private ApplicationContext applicationContext;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //将传入的JSON转成AuthParamsDto对象
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s,AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求的参数不符合要求");
        }
        //认证类型,
        String authType = authParamsDto.getAuthType();
        //拼接beanName
        String beanName = authType + "_authservice";
        //根据认证类型，获取不同的bean进行处理
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        //调用bean方法,得到用户信息
        YxyUserExt execute = authService.execute(authParamsDto);
        //将YxyUserExt封装为UserDetails
        UserDetails userDetails = getUserPrincipal(execute);
        return userDetails;
    }
    /**
     * @description 查询用户信息
     * @param xcUser  用户id，主键
     * @return com.yixueyun.ucenter.model.po.YxyUser 用户信息
     */
    public UserDetails getUserPrincipal(YxyUserExt xcUser){
        String password = xcUser.getPassword();
        //封装数据 用户名、密码、权限
        xcUser.setPassword(null);
        String userJSON = JSON.toJSONString(xcUser);
        //默认权限
        String[] authorities = {"test"};
        //根据用户id查询权限，插入令牌中
        List<YxyMenu> yxyMenus = yxyMenuMapper.selectPermissionByUserId(xcUser.getId());
        if(yxyMenus.size() > 0 ) {
            ArrayList<String> permissions = new ArrayList<>();
            yxyMenus.forEach(m ->{
                permissions.add(m.getCode());
            });
            authorities = permissions.toArray(new String[0]);
        }

        UserDetails userDetails = User.withUsername(userJSON).password(password).authorities(authorities).build();
        return userDetails;
    }
}
